<?php
/**
 * DouPHP小程序模块
 * Author: cuihaifeng  qq 366131726 微信同号
 * 网址：www.zbxingke.com www.0533hf.com
 */
if (!defined('IN_DOUCO_API')) {
    die('Access Denied');
}

/**
 * 收藏取消收藏
 */
function doPageHandle(){
    global $_GPC, $_W;

    $page_id = $_GPC["page_id"];
    $user_id = $_GPC["user_id"];
    $page_type = $_GPC['page_type'];

    if (!$user_id) {
        $user = get_user_by_openid(wxapp_getopenid());
        $user_id = $user['user_id'];
    }

    $collect = pdo_fetch("SELECT * FROM " . tablename("page_collect") . " WHERE user_id = :user_id AND page_type = :page_type and page_id = :page_id", array(":user_id" => $user_id, ":page_type" => $page_type, ":page_id" => $page_id));
    if ($collect) {
        $res = pdo_delete("page_collect", array( "id" => $collect['id']));
        if ($res) {
            return wxapp_result(0, "success", "取消收藏成功");
        }
    } else {
        $data = array("user_id" => $user_id, "page_type" => $page_type, "page_id" => $page_id,'title'=>$_GPC['title']);
        $res = pdo_insert("page_collect", $data);
        if ($res) {
            return wxapp_result(0, "success", "收藏成功");
        }
    }
    return wxapp_result(404, "error", "收藏失败，会员模块未开启！");
}

/**
 * 获取用户的收藏
 */
function doPageGet(){
    global $_GPC,$_W;
    $user_id = $_GPC['user_id'] ? $_GPC['user_id'] : get_user_by_openid(wxapp_getopenid());
    $pindex = max(1, intval($_GPC["page"]));
    $psize = 10;

    $where = " WHERE user_id = :user_id";
    $params['user_id'] = $user_id;


    $data['num'] = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename("page_collect") . $where,$params);
    $data['page_size'] = $psize;
    $data["list"] = pdo_fetchall("SELECT * FROM " . tablename("page_collect") .  $where . " ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . "," . $psize,$params);

    return wxapp_result(0,'success',$data);
}